package com.uchiha.nova.mainService.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.obs.services.ObsClient;
import com.uchiha.nova.core.tool.api.R;
import com.uchiha.nova.core.tool.util.PicUtils;
import com.uchiha.nova.mainService.service.UploadFileToHuaweiService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @Author 周林静
 * @Date 2025-07-21 11:16
 * @Version 1.0
 */
@Service
@Slf4j
public class UploadFileToHuaweiServiceImpl implements UploadFileToHuaweiService {
    @Value("${huawei-cloud.obs.accessKey}")
    private String accessKey;

    @Value("${huawei-cloud.obs.securityKey}")
    private String securityKey;

    @Value("${huawei-cloud.obs.endpoint}")
    private String endpoint;

    @Value("${huawei-cloud.obs.bucketName}")
    private String bucketName;

    @Override
    public R uploadImage(MultipartFile file, String name, String path)  {
        ByteArrayInputStream inputStream = null;
        try {
             inputStream = new ByteArrayInputStream(file.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }


        String originalFileName = file.getOriginalFilename();
        String hbane =  originalFileName.substring(originalFileName.lastIndexOf("."));
        if(ObjectUtil.isEmpty(name)){
            name = file.getOriginalFilename();
        }else{
            name=name+hbane;
        }

        String fileName = UUID.randomUUID()+hbane;
        if(ObjectUtil.isNotEmpty(path)){
            fileName = path+"/"+fileName;
        }
        ObsClient obsClient = new ObsClient(accessKey, securityKey, endpoint);
        obsClient.putObject(bucketName, fileName, inputStream);
        Map<String,Object> map = new HashMap<>();
        map.put("url","https://"+bucketName+"."+endpoint+"/"+fileName);
        map.put("name",name);
        return R.data(map);
    }
}
